﻿using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using System;
using System.Collections.Generic;
using System.Text;

namespace SX.Core.MongoDB
{
    /// <summary>
    /// BsonDocument扩展 如果要把实体变为BsonDocument使用Bson扩展方法 ToBsonDocument()
    /// </summary>
    public static class BsonExtension
    {
        /// <summary>
        /// BsonDocument集合转为实体集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="bsons"></param>
        /// <returns></returns>
        public static IList<T> ToEntityList<T>(this IEnumerable<BsonDocument> bsons)
        {
            IList<T> list = new List<T>();
            foreach (var item in bsons)
                list.Add(BsonSerializer.Deserialize<T>(item));
            return list;
        }

        /// <summary>
        /// BsonDocument对象转为实体对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="bson"></param>
        /// <returns></returns>
        public static T ToEntityList<T>(this BsonDocument bson)
        {
            var data= BsonSerializer.Deserialize<T>(bson);
            return data;
        }
    }
}
